import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class UDPClient {
    private DatagramSocket socket = null;
    private String serverIp;
    private int serverPort;
    //1.构造客户端
    //  获取服务器Ip和端口号
    public UDPClient(String serverIp,int serverPort) throws SocketException {
        this.socket = new DatagramSocket();
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }
    //2.客户端启动
    private void start() throws IOException {
        Scanner scanner = new Scanner(System.in);
        while (true){
            System.out.println("输入请求->");
            String request = scanner.next();
            if (request.equals("NO")){
                return;
            }
            //构造请求数据包
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                                                              InetAddress.getByName(serverIp),serverPort);
            //发送请求数据包
            socket.send(requestPacket);
            //接收响应数据包
            DatagramPacket responsePacket = new DatagramPacket(new byte[2],2);
            socket.receive(responsePacket);
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            String log = String.format("req:%s,res:%s", request,response);
            System.out.println(log);
        }
    }

    public static void main(String[] args) throws IOException {
        UDPClient udpClient = new UDPClient("127.0.0.1",9999);
        udpClient.start();
    }
}
